<?php 
// --------------------------------------------------------------------

/**
 * js_datepicker
 *
 * return media file for datepicker
 *
 * @access	public
 * @param	string
 * @return	str
 */	
if ( ! function_exists('js_datepicker'))
{	
	function js_datepicker($selector=".datepicker")
	{		
		$js = '<link rel="stylesheet" href="js/date_input/date_input.css" type="text/css" media="screen" />';
		$js .= '<script type="text/javascript" src="js/date_input/jquery.date_input.min.js"></script>';
		$js .= '<script type="text/javascript" src="js/date_input/jquery.date_input.th.js"></script>';
		$js .= '<script type="text/javascript">
					$(function(){
						$("input.datepicker").date_input(); 
					});
				</script>';
		return $js; 
	}
}

// --------------------------------------------------------------------
if(!function_exists('js_number'))
{
	function js_number($selector=".number")
	{
		$js = '<script type="text/javascript" src="js/jquery.price_format.1.3.js"></script>';
		$js .= '<script type="text/javascript">
					$(function(){
						$("'.$selector.'").priceFormat({prefix: "",thousandsSeparator: ","}); 
					});
				</script>';
		return $js; 
	}
}

if(!function_exists('js_print'))
{
	function js_print()
	{
		$js = '<script type="text/javascript">
   				$(function(){
				$(\'#content\').append(\'<div class="print-box"> \
				<a class="button" href="#print"><span class="icon_text print"></span>พิมพ์หน้านี้</a> \
				</div>\');
				})
				</script>';
		return $js; 
	}
}

if(!function_exists('set_notify'))
{
	function set_notify($type,$msg)
	{
		$config = array(
			'notify' => TRUE,
			'type' => $type,
			'msg' => $msg
		);
		$CI =& get_instance();
		$CI->session->set_flashdata($config);
	}
}

if(!function_exists('get_one'))
{
	function get_one($field,$table,$id='id',$value)
	{
		$CI =& get_instance();
		$result = $CI->db->getone('select '.$field.' from '.$table.' where '.$id.' = ?',$value);
		dbConvert($result);
		return $result;
	}
}

if(!function_exists('notify'))
{
	function js_notify()
	{
		$CI =& get_instance();
		if($CI->session->flashdata('notify'))
		{
			$js = '<link rel="stylesheet" href="js/jquery.notifyBar.css" type="text/css" media="screen" />';
		    $js .= '<script type="text/javascript" src="js/jquery.notifyBar.js"></script>';
		    $js .= '<script type="text/javascript">
		    				$(function () {
						  		$.notifyBar({
						  			cls:"'.$CI->session->flashdata('type').'",
						    		html: "'.$CI->session->flashdata('msg').'",
						    		delay: 2000,
						    		animationSpeed: "normal"
						  		});  
							});
						</script>';
			return $js; 
		}
	}
}
//$type -> attention information success error
if(!function_exists('set_caution'))
{
	function set_caution($type,$msg,$selector=".block_content",$position="prepend")
	{
		$config = array(
			'caution' => TRUE,
			'type' => $type,
			'msg' => $msg,
			'position' => $position,
			'selector' => $selector
		);
		$CI =& get_instance();
		$CI->session->set_flashdata($config);
	}
}

if(!function_exists('caution'))
{
	function caution()
	{
		$CI =& get_instance();
		if($CI->session->flashdata('caution'))
		{
		    $js = '<div class="notification '.$CI->session->flashdata('type').' png_bg"><div>'.$CI->session->flashdata('msg').'</div></div>';
			return $js; 
		}
	}
}

if(!function_exists('js_caution'))
{
	function js_caution()
	{
		$CI =& get_instance();
		if($CI->session->flashdata('caution'))
		{
		    $html = "<div class='notification ".$CI->session->flashdata('type')." png_bg'><div>".$CI->session->flashdata('msg')."</div></div>";
			$js = '<script type="text/javascript">
		    				$(function () {
						  		$("'.$CI->session->flashdata('selector').'").'.$CI->session->flashdata('position').'("'.$html.'") 
							});
						</script>';
			return $js; 
		}
	}
}

if(!function_exists('menu_active'))
{
	function menu_active($module,$controller = FALSE,$class='active')
	{
		$CI =& get_instance();
		if($controller)
		{
			return ($CI->router->fetch_module() == $module && $CI->router->fetch_class() == $controller) ? 'class='.$class : '';	
		}
		else
		{
			return ($CI->router->fetch_module() == $module) ? 'class='.$class : '';	
		}
	}
}

function cycle($key,$odd = 'odd',$even = 'even')
{
	return ($key&1) ? 'class="'.$even.'"' : 'class="'.$odd.'"';
}

function get_option($value,$text,$table,$where = FALSE)
{
	$CI =& get_instance();
	$where = ($where) ? 'where '.$where : '';
	$result = $CI->db->GetAssoc('select '.$value.','.$text.' from '.$table.' '.$where);
	array_walk($result,'dbConvert');
	return $result;
}

function pagebreak($content){
	$break = '<div style="page-break-after: always;"><span style="display: none;">&nbsp;</span></div>';
	return substr("$content",0,strpos($content,$break)+strlen($break));
	//return    strstr($content, '<div style="page-break-after: always;"><span style="display: none;">&nbsp;</span></div>',TRUE); // for PHP 5.3.0
}

function getIP(){
    $ip = (getenv(HTTP_X_FORWARDED_FOR))
    ?  getenv(HTTP_X_FORWARDED_FOR)
    :  getenv(REMOTE_ADDR);
    return $ip;
}

function currency_rate($price)
{
	$CI =& get_instance();
	$CI->load->model('currency/currency_model');
	$currency = $CI->currency_model->get_active_rate($CI->session->userdata('currency'));
	return number_format(($price * $currency['rate']),2).' '.$currency['currency'];
}

// js syntaghighlight
function js_syntax()
{
	return '<script type="text/javascript" src="js/sysntaxhighilight/scripts/shCore.js"></script>
			<script type="text/javascript" src="js/sysntaxhighilight/scripts/shBrushBash.js"></script>
			<script type="text/javascript" src="js/sysntaxhighilight/scripts/shBrushCpp.js"></script>
			<script type="text/javascript" src="js/sysntaxhighilight/scripts/shBrushCSharp.js"></script>
			<script type="text/javascript" src="js/sysntaxhighilight/scripts/shBrushCss.js"></script>
			<script type="text/javascript" src="js/sysntaxhighilight/scripts/shBrushDelphi.js"></script>
			<script type="text/javascript" src="js/sysntaxhighilight/scripts/shBrushDiff.js"></script>
			<script type="text/javascript" src="js/sysntaxhighilight/scripts/shBrushGroovy.js"></script>
			<script type="text/javascript" src="js/sysntaxhighilight/scripts/shBrushJava.js"></script>
			<script type="text/javascript" src="js/sysntaxhighilight/scripts/shBrushJScript.js"></script>
			<script type="text/javascript" src="js/sysntaxhighilight/scripts/shBrushPhp.js"></script>
			<script type="text/javascript" src="js/sysntaxhighilight/scripts/shBrushPlain.js"></script>
			<script type="text/javascript" src="js/sysntaxhighilight/scripts/shBrushPython.js"></script>
			<script type="text/javascript" src="js/sysntaxhighilight/scripts/shBrushRuby.js"></script>
			<script type="text/javascript" src="js/sysntaxhighilight/scripts/shBrushScala.js"></script>
			<script type="text/javascript" src="js/sysntaxhighilight/scripts/shBrushSql.js"></script>
			<script type="text/javascript" src="js/sysntaxhighilight/scripts/shBrushVb.js"></script>
			<script type="text/javascript" src="js/sysntaxhighilight/scripts/shBrushXml.js"></script>
			<link type="text/css" rel="stylesheet" href="js/sysntaxhighilight/styles/shCore.css"/>
			<link type="text/css" rel="stylesheet" href="js/sysntaxhighilight/styles/shThemeDefault.css"/>
			<script type="text/javascript">
				SyntaxHighlighter.config.clipboardSwf = "js/sysntaxhighilight/scripts/clipboard.swf";
				SyntaxHighlighter.all();
			</script>';
}

function js_validate()
{
	return '<script type="text/javascript" src="js/jquery.validate.min.js"></script>';
}

function js_ckeditor()
{
	return '<script type="text/javascript" src="ckeditor/ckeditor.js"></script>';
}

// --------------------------------------------------------------------
if(!function_exists('js_checkbox'))
{
	function js_checkbox($mode=FALSE)
	{
		return '<link rel="stylesheet" href="js/checkbox/jquery.checkbox.css" />
			<script type="text/javascript" src="js/checkbox/jquery.checkbox.min.js"></script>
			<script>
				$(function(){
					$("input:checkbox,input:radio").checkbox({empty:"js/checkbox/empty.png"});
				});
			</script>';
	}
}

// --------------------------------------------------------------------



if (!function_exists('json_encode'))
{
 function json_encode($a=false)
 {
 if (is_null($a)) return 'null';
 if ($a === false) return 'false';
 if ($a === true) return 'true';
 if (is_scalar($a))
 {
 if (is_float($a))
 {
 // Always use "." for floats.
 return floatval(str_replace(",", ".", strval($a)));
 }

 if (is_string($a))
 {
 static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
 return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
 }
 else
 return '"'.$a.'"';
 }
 $isList = true;
 for ($i = 0, reset($a); $i < count($a); $i++, next($a))
 {
 if (key($a) !== $i)
 {
 $isList = false;
 break;
 }
 }
 $result = array();
 if ($isList)
 {
 foreach ($a as $v) $result[] = json_encode($v);
 return '[' . join(',', $result) . ']';
 }
 else
 {
 foreach ($a as $k => $v) $result[] = json_encode($k).':'.json_encode($v);
 return '{' . join(',', $result) . '}';
 }
 }
}

function get_settingDate()
{
	$data = range(1,28);
	return array_combine($data, $data);
}

function dbConvert(&$value,$key = null,$output='UTF-8')
{
	$encode = array('UTF-8'=>'TIS-620','TIS-620'=>'UTF-8');
	if(is_array($value))
	{
		$value = array_change_key_case($value);
		array_walk($value,'dbConvert',$output);
	}
	else
	{
		$value = iconv($encode[$output],$output,$value);
	}
}

function fixDate($fund_id,$date = FALSE)
{
	$CI =& get_instance();
	$user = login_data();
	if(empty($date))
	{
		//$CI->db->debug = TRUE;
		$item = $CI->db->getRow('
		select 
		MONTH(vouchers.voucher_date) month_balance,
		YEAR(vouchers.voucher_date) year_balance 
		from	(
				select * 
				from vouchers 
				where id = (
							select max(id) 
							from vouchers 
							where vouchers.is_balance = 1 
							and vouchers.agency_id = '.$user['agency_id'].' 
							and vouchers.fund_id = '.$fund_id.')
							) vouchers 
		');
		dbConvert($item);
		if(!empty($item['year_balance']))
		{
			$date = $item['year_balance'].'-'.substr('0'.$item['month_balance'],-2).'-01';
		}
		else
		{
			return false;
		}
	}
	return 'rel="'.mysql_to_date($date,TRUE).'"';
}

function status($date)
{
	$CI =& get_instance();
	$user = login_data();
	$data = $CI->db->getRow('
		select 
		voucher_balances.month_record,
		voucher_balances.year_record,
		MONTH(vouchers.voucher_date) month_balance,
		YEAR(vouchers.voucher_date) year_balance 
		(select * from voucher_balances where voucher_balances.agency_id = '.$user['agency_id'].' voucher_balances.fund_id = '.$user['fund_id'].') voucher_balances
		left join (select * from vouchers where vouchers.is_balance = 1 and vouchers.agency_id = '.$user['agency_id'].' and vouchers.fund_id = '.$user['fund_id'].') vouchers 
		on voucher_balances.agency_id = vouchers.agency_id
		where agencies.id <> 1
	');
}

function get_agency_option($fund_id = FALSE)
{
	switch ($fund_id) {
    case 1:
        return get_option('id','name','agencies','id not in (1,79)');
        break;
    case 2:
        return get_option('id','name','agencies','id in (2,79)');
        break;
	case 3:
        return get_option('id','name','agencies','id in (2,79)');
        break;
    default:
       return get_option('id','name','agencies');
}
}

function add_log($detail)
{
	$CI =& get_instance();
	$user = login_data();
	$CI->load->model('log/log_model','log');
	$data['detail'] = $detail;
	$data['user_id'] = $user['id'];
	$data['ip'] = $CI->session->userdata['ip_address'];
	$data['log_date'] = time();
	if(is_login())
	{
		$CI->log->save($data);
		return TRUE;
	}
	else
	{
		return FALSE;
	}
}

function pre_dump($var)
{
	echo "<pre>";
	var_dump($var);
	echo "</pre>";
}

function remain_notice($fund_id)
{
	$CI =& get_instance();
	$user = login_data();
	$status = $CI->db->getRow('
	select * 
	from status 
	where id = (select max(id) from status where fund_id = '.$fund_id.' 
	and agency_id = '.$user['agency_id'].')
	');
	dbConvert($status);

	if($status['status']=='1')
	{
		$html = '<div class="header-notice">';
		$html .= ($remain >=0)?'<img src="themes/fund/images/icon/time.png" style="width:40px;height:40px;" />':'<img src="themes/fund/images/warning.png" style="width:40px;height:40px;" />';
		$html .= get_one('name','funds','id',$fund_id).'<br />';
		$html .= 'กำหนดส่งข้อมูลภายในวันที่ '.db_to_th($status['status_year'].'-'.substr('0'.($status['status_month']),-2).'-'.substr('0'.get_one('value','settings','id',$fund_id),-2)).'<br />';
		$html .= 'รอการตรวจสอบ';
		$html .= '<br style="clear:both;" />';
		$html .= '</div>';
		//echo $status['status_year'].'-'.substr('0'.($status['status_month']),-2).'-'.substr('0'.get_one('value','settings','id',$fund_id),-2);
		return $html;
	}
	
	$balance_date = $CI->db->getOne('select max(voucher_date) from vouchers where is_balance = 1 and fund_id = '.$fund_id.' and agency_id = '.$user['agency_id']);
	if($balance_date)
	{
		$balance_date = explode('-', $balance_date);
		$date = $balance_date[0].'-'.substr('0'.($balance_date[1]),-2).'-'.substr('0'.get_one('value','settings','id',$fund_id),-2);
		/*
		if((date('d')>get_one('value','settings','id',$fund_id))&&(date('m')<date('m',strtotime($date))))
		{
			$ex_date = $date;
		}
		else
		{
			$ex_date = date("Y-m-d",strtotime(date("Y-m-d", strtotime($date)) . " +1 month"));
		}
		*/
		//$ex_date = (date('d')>get_one('value','settings','id',$fund_id))?date("Y-m-d",strtotime(date("Y-m-d", strtotime($date)) . " +1 month")):$date;
		//echo $date;
		$ex_date = date("Y-m-d",strtotime(date("Y-m-d", strtotime($date)) . " +1 month"));
		$fund = get_one('name','funds','id',$fund_id);
		
		$remain = DateDiff(date('Y-m-d'),$ex_date);
		
		$html = '<div class="header-notice">';
		$html .= ($remain >=0)?'<img src="themes/fund/images/icon/time.png" style="width:40px;height:40px;" />':'<img src="themes/fund/images/warning.png" style="width:40px;height:40px;" />';
		$html .= $fund.'<br />';
		$html .= 'กำหนดส่งข้อมูลภายในวันที่ '.db_to_th($ex_date).'<br />';
		
		if($remain >= -3)
		{
			if($remain < 0)
			{
				$html .= '<span class="red">เลยกำหนดเวลาในการส่งข้อมูล '.($remain * -1).' วัน</span><br />';
			}
			else
			{
				$html .= 'เหลือเวลาในการส่งข้อมูล '.$remain.' วัน<br />';
			}
			$html .= '<a style="display:block; float:right; margin:5px 0 0 0;" class="button" href="voucher/complete/'.$fund_id.'"><span class="icon_text send"></span>ส่งข้อมูล</a>';
		}
		else
		{
			$html .= '<span class="red">เลยกำหนดเวลาในการส่งข้อมูล '.($remain * -1).' วัน</span><br />';
			if(($CI->db->getOne('select is_lock from agency_details where fund_id = ? and agency_id = ?',array($fund_id,$user['agency_id']))=='0')OR($status['status']=='3'))
			{
				if($status['status']==3)
				{
					$html .= '<a style="display:block; float:right; margin:5px 0 0 0;" class="button" href="voucher/complete/'.$fund_id.'"><span class="icon_text send"></span>ส่งข้อมูล</a>';
				}
				else
				{
					$html .= '<a style="display:block; float:right; margin:5px 0 0 0;" class="button" href="voucher/complete/'.$fund_id.'"><span class="icon_text send"></span>ส่งข้อมูล</a>';
				}
			}
		}
		
		
		$html .= '<br style="clear:both;" />';
		$html .= '</div>';
		return $html;
	}
	else
	{
		return FALSE;
	}
}

function voucher_lock($data)
{
	if($data['agency_id']<> login_data('agency_id'))return FALSE;
	$CI =& get_instance();
	$voucher_date = explode('-',$data['voucher_date']);
	$balance_date = $CI->db->getOne('select max(voucher_date) from vouchers where is_balance = 1 and fund_id = '.$data['fund_id'].' and agency_id = '.$data['agency_id']);
	$balance_date = explode('-',$balance_date);
	$is_lock = $CI->db->getOne('select is_lock from agency_details where fund_id = ? and agency_id = ?',array($data['fund_id'],$data['agency_id']));
	
	$date = $voucher_date[0].'-'.substr('0'.($voucher_date[1]),-2).'-'.substr('0'.get_one('value','settings','id',$data['fund_id']),-2);
	//echo pre_dump($balance_date);
	if((date('d')>get_one('value','settings','id',$fund_id))&&(date('m')<date('m',strtotime($date))))
	{
		$expire_date = $date;
	}
	else
	{
		$expire_date = date("Y-m-d",strtotime(date("Y-m-d", strtotime($date)) . " +1 month"));
	}

	$remain = DateDiff(date('Y-m-d'),$expire_date);
	
	$status = $CI->db->getOne('
	select status 
	from status 
	where fund_id = '.$data['fund_id'].' 
	and agency_id = '.$data['agency_id'].' 
	and status_year = '.$voucher_date[0].' 
	and status_month ='.$voucher_date[1]);
	if($data['is_balance']=='1')
	{
		if(
		($data['voucher_date']==$CI->db->getOne('select min(voucher_date) from vouchers where is_balance = 1 and fund_id = '.$data['fund_id'].' and agency_id = '.$data['agency_id']))
		&&($CI->db->getOne('select count(voucher_date) from vouchers where is_balance = 1 and fund_id = '.$data['fund_id'].' and agency_id = '.$data['agency_id'])==1)
		&&(($CI->db->getOne('select COALESCE(is_lock,1) from agency_details where fund_id = ? and agency_id = ?',array($data['fund_id'],$data['agency_id']))=='0')OR($status == 3)OR($remain>0))
		)
		{
			return TRUE;
		}
		else
		{
			return FALSE;
		}
	}

	if(($status == '1')OR($status == '2'))
	{
		return FALSE;
	}
	elseif($status == '3')
	{
		return TRUE;
	}
	
	
	if(($is_lock=='0')&&($balance_date[0].'-'.$balance_date[1]==$voucher_date[0].'-'.$voucher_date[1]))
	{
		return TRUE;
	}
	
	if($remain < -3)
	{
		return FALSE;
	}
	else
	{
		return TRUE;
	}
	
}

function check_status($fund_id,$agency_id)
{
	//if($agency_id<> login_data('agency_id'))return FALSE;
	$CI =& get_instance();
	$status = $CI->db->getOne('
	select status 
	from status 
	where id = (select max(id) from status where fund_id = '.$fund_id.' 
	and agency_id = '.$agency_id.')
	');
	$is_lock = $CI->db->getOne('select is_lock from agency_details where fund_id = ? and agency_id = ?',array($fund_id,$agency_id));
	if($is_lock == '0')return TRUE;
	if($status == '1')
	{
		return FALSE;
	}
	elseif($status == '3')
	{
		return TRUE;
	}
	else
	{
		$balance_date = $CI->db->getOne('select max(voucher_date) from vouchers where is_balance = 1 and fund_id = '.$fund_id.' and agency_id = '.$agency_id);
		if($balance_date)
		{
			$balance_date = explode('-', $balance_date);
			$date = $balance_date[0].'-'.substr('0'.($balance_date[1]),-2).'-'.substr('0'.get_one('value','settings','id',$fund_id),-2);
			
			if((date('d')>get_one('value','settings','id',$fund_id))&&(date('m')<date('m',strtotime($date))))
			{
				$expire_date = $date;
			}
			else
			{
				$expire_date = date("Y-m-d",strtotime(date("Y-m-d", strtotime($date)) . " +1 month"));
			}
			$remain = DateDiff(date('Y-m-d'),$expire_date);
			//echo $remain;
			if($remain < -3)
			{
				return FALSE;
			}
			else
			{
				return TRUE;
			}
			
		}
		else
		{
			return TRUE;
		}
	}
}


function is_first_use($fund_id, $agency_id)
{
	$id = get_instance()->db->getrow('SELECT ID FROM STATUS WHERE FUND_ID = ? AND AGENCY_ID = ?', array($fund_id, $agency_id));
	return empty($id) ? TRUE : FALSE;
}

function fund1_first_use($fund_id, $agency_id)
{
	$id = get_instance()->db->getrow('select id from vouchers where fund_id = 1 and is_balance = 1 and vouchers.agency_id = '.login_data('agency_id'));
	return empty($id) ? TRUE : FALSE;
}


function check_current_year_month($fund_id, $agency_id)
{
	return get_instance()->db->getrow('SELECT STATUS_YEAR, STATUS_MONTH 
	FROM STATUS
	WHERE FUND_ID = ?
	AND AGENCY_ID = ?
	ORDER BY STATUS_YEAR DESC, STATUS_MONTH DESC', array($fund_id, $agency_id));
}

function last_status($fund_id)
{
	$CI =& get_instance();
	$user = login_data();
	$status = $CI->db->getRow('
	select * 
	from status 
	where id = (select max(id) from status where fund_id = '.$fund_id.' 
	and agency_id = '.$user['agency_id'].')
	');
	dbConvert($status);
	return $status;
}

function close_budget($fund_id)
{
	$status = last_status($fund_id);
	if(($status['status_month']=='9')&&($status['status']=='2'))
	{
		return TRUE;
	}
	else
	{
		return FALSE;
	}
}
?>